package com.alibaba.algo.controller.user;

import com.alibaba.algo.annotation.OperateLogAnnotation;
import com.alibaba.algo.apiimpl.user.SysPositionServiceImpl;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.common.SysConstant;
import com.alibaba.algo.cooperation.usercenter.GlobalResultStatus;
import com.alibaba.algo.cooperation.usercomponent.vo.req.user.*;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.SelectPositionListResponseVO;
import com.alibaba.algo.core.base.PagerEntity;
import com.alibaba.algo.entity.user.SysPosition;
import com.alibaba.algo.enums.OperateTypeEnum;
import com.alibaba.algo.enums.ResourceTypeEnum;
import com.alibaba.algo.exception.SysPositionErrorCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 类SysPositionController.java的实现描述：岗位 Controller
 *
 * @author nieganggang 2021-03-12 16:08:17
 */
@RestController
@RequestMapping(value = "/usercenter-admin-app/admin/sysPosition")
@Api(tags = "岗位管理")
public class SysPositionController {

    @Autowired
    private SysPositionServiceImpl sysPositionService;

    /**
     * 新增岗位
     *
     * @param createPositionRequestVOList 列表
     * @return
     */
    @PostMapping("/insert")
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.POSITION,operateType = OperateTypeEnum.INSERT)
    public BaseResult insert(@RequestBody List<CreatePositionRequestVO> createPositionRequestVOList) {
        if (CollectionUtils.isEmpty(createPositionRequestVOList)) {
            return BaseResult.buildSuccess();
        }
        SelectPositionListRequestVO vo = new SelectPositionListRequestVO();
        if(!ObjectUtils.isEmpty(createPositionRequestVOList)){//参数根据名称去重（在同组织下）
            createPositionRequestVOList = createPositionRequestVOList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CreatePositionRequestVO::getName))), ArrayList::new));
            List<String> posNameList = new ArrayList<>();
            createPositionRequestVOList.forEach(item -> {
                posNameList.add(item.getName());
                vo.setOrgId(item.getOrgId());
            });
            vo.setPosNameList(posNameList);
        }
        //根据组织id、岗位名称查询重复记录
        BaseResult result = sysPositionService.qryPositionListByOrgIdAndName(vo);
        if(!ObjectUtils.isEmpty(result) && SysConstant.OK.equals(result.getCode())){
            if(null != result.getData()){
                List<SysPosition> sysPositionList = (List<SysPosition>)result.getData();
                if(!ObjectUtils.isEmpty(sysPositionList)){
                    for(SysPosition sysPosition : sysPositionList){
                        createPositionRequestVOList.removeIf(item -> {
                            return item.getName().equals(sysPosition.getName());
                        });
                    }
                }
            }
        }
        if(ObjectUtils.isEmpty(createPositionRequestVOList)){
            return BaseResult.buildError(SysPositionErrorCode.DUPLICATE_POS_NAME_IN_SAME_ORG.getCode(),SysPositionErrorCode.DUPLICATE_POS_NAME_IN_SAME_ORG.getMessage());
        }
        return sysPositionService.save(createPositionRequestVOList);
    }

    @PostMapping("/update/main")
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.POSITION,operateType = OperateTypeEnum.UPDATE)
    public BaseResult updateMain(@RequestBody UpdatePositionRequestVO vo) {
        if (ObjectUtils.isEmpty(vo.getId())) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getCode(), GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getMsg());
        }
        return sysPositionService.updateMain(vo);
    }

    @PostMapping("/update/nonMain")
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.POSITION,operateType = OperateTypeEnum.UPDATE)
    public BaseResult updateNonMain(@RequestBody UpdatePositionRequestVO vo) {
        if (ObjectUtils.isEmpty(vo.getId())) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getCode(), GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getMsg());
        }
        return sysPositionService.updateNonMain(vo);
    }

    @PostMapping("/delete")
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.POSITION,operateType = OperateTypeEnum.DELETE)
    public BaseResult delete(@RequestBody List<Long> vo) {
        if (CollectionUtils.isEmpty(vo)) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getCode(), GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getMsg());
        }
        return sysPositionService.delete(vo);
    }

    @PostMapping("/qryAllPositions")
    public BaseResult qryAllPositions() {
        return sysPositionService.qryAllPositions();
    }

    @PostMapping("/qryPositionListByOrgId")
    public BaseResult qryPositionListByOrgId(@RequestBody SelectOrgPositionReqVO vo) {
        return sysPositionService.qryPositionListByOrgId(vo);
    }

    @PostMapping("/selectPage")
    public BaseResult<PagerEntity<SelectPositionListResponseVO>> selectPage(@RequestBody SelectPositionListRequestVO vo) {
//        if (StringUtils.isEmpty(vo.getOrgId())) {
//            return BaseResult.buildError(GlobalResultStatus.PARAM_SYS_ORG_ID_ERROR.getCode(), GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getMsg());
//        }
        if (ObjectUtils.isEmpty(vo.getPageIndex())) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getMsg());
        }
        if (ObjectUtils.isEmpty(vo.getPageSize())) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getMsg());
        }
        return sysPositionService.selectPage(vo);
    }


    @GetMapping("/position/{id}")
    public BaseResult<SelectPositionListResponseVO> getById(@PathVariable("id") Long id) {
        return sysPositionService.getById(id);
    }

    @PostMapping("/listDistinctPositionNames")
    public BaseResult listDistinctPositionNames() {
        return BaseResult.buildSuccess(sysPositionService.listDistinctPositionNames());
    }

    ;

    @PostMapping("/updatePosition")
    @ApiOperation(value = "岗位更新")
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.POSITION,operateType = OperateTypeEnum.UPDATE)
    public BaseResult updatePosition(@Valid @RequestBody UpdatePositionRequestVO vo) {
        if (ObjectUtils.isEmpty(vo.getId())) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getCode(), GlobalResultStatus.PARAM_SYS_POSITION_ID_ERROR.getMsg());
        }
        return sysPositionService.updatePosition(vo);
    }


    @PostMapping("/addPosition")
    @ApiOperation(value = "岗位新增")
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.POSITION,operateType = OperateTypeEnum.INSERT)
    public BaseResult addPosition(@Valid @RequestBody CreatePositionReqVo vo) {
        return sysPositionService.addPosition(vo);
    }

}
